from django.shortcuts import render
from django.views import View
from django.http import JsonResponse
from django.core.cache import cache

from meiduo.utils.response_code import *
from meiduo.utils.judgelogin import UserLoginView
from areas.models import Areas
from areas import constants


class AreasShow(UserLoginView):
    """获取各个区域名称"""
    def get(self,request):
        area_id = request.GET.get("area_id")
        if area_id is None:
            # 查询所有省份

            provinces_list = cache.get("province_list")
            # 利用缓存  在缓存中查看有无数据

            if not provinces_list:
                # 缓存中未获取到数据  在数据库中查找
                provinces = Areas.objects.filter(parent_id__isnull=True)
                provinces_list = []
                """将省份模型转换为列表格式"""
                for province in provinces:
                    id = province.id
                    name = province.area_name
                    provinces_list.append({"id":id,"name":name})

                cache.set("province_list",provinces_list,constants.province_cache_time)
                # 在缓存中存取数据
            return JsonResponse({"code":RETCODE.OK,"errmsg":"OK","province_list":provinces_list})

        else:
            # 查询城市 区县
            try:
                parent = Areas.objects.get(id=area_id)
                citys = parent.subs.all()
                # 查询出area_id对应的所有的城市
                city_list = cache.get("city_%s"%parent.area_name)
                # 在缓存中尝试获取数据

                if not city_list:
                    city_list =[]
                    """将城市对象集合转化为列表格式"""
                    for city in citys:
                        id = city.id
                        name = city.area_name
                        city_list.append({"id":id,"name":name})
                    # 存储在缓存中
                    cache.set("city_%s"%parent.area_name,city_list,constants.city_cache_time)
                sub_data = {"id":parent.id,"name":parent.area_name,"subs":city_list}

                return JsonResponse({"code":RETCODE.OK,"errmsg":"OK","sub_data":sub_data})
            except:
                return render(request,"404.html")
